//
//  IMNetworkUsageExample.m
//  DualMediationSDK
//
//  Created by YeJary on 2025/6/23.
//

#import <Foundation/Foundation.h>
#import "IMNetworkUtils.h"
#import "IMLogUtils.h"

/**
 * IMNetworkUtils 使用示例
 * 
 * 演示网络工具类的各种功能：
 * - 基础HTTP请求
 * - 文件上传下载
 * - 网络状态监控
 * - 请求管理
 * - 错误处理
 */
@implementation NSObject (IMNetworkUsageExample)

#pragma mark - 基础示例

+ (void)basicNetworkExample {
    NSLog(@"========== 网络工具基础示例 ==========");
    
    // 1. 初始化网络工具
    IMNetworkConfig *config = [IMNetworkConfig defaultConfig];
    config.baseURL = @"https://jsonplaceholder.typicode.com";
    config.timeoutInterval = 30.0;
    config.enableLogging = YES;
    
    [IMNetworkUtils initWithConfig:config];
    
    // 2. GET请求示例
    [self demonstrateGETRequest];
    
    // 3. POST请求示例
    [self demonstratePOSTRequest];
    
    // 4. 文件操作示例
    [self demonstrateFileOperations];
    
    // 5. 网络状态监控示例
    [self demonstrateNetworkMonitoring];
    
    // 6. 请求管理示例
    [self demonstrateRequestManagement];
}

+ (void)demonstrateGETRequest {
    NSLog(@"\n--- GET请求示例 ---");
    
    // 简单GET请求
    [IMNetworkUtils GET:@"/posts/1"
             parameters:nil
                success:^(IMNetworkResponse *response) {
                    NSLog(@"✅ GET请求成功:");
                    NSLog(@"状态码: %ld", (long)response.statusCode);
                    NSLog(@"耗时: %.3fs", response.duration);
                    NSLog(@"数据: %@", response.data);
                }
                failure:^(IMNetworkResponse *response) {
                    NSLog(@"❌ GET请求失败:");
                    NSLog(@"错误: %@", response.error.localizedDescription);
                }];
    
    // 带参数的GET请求
    NSDictionary *params = @{
        @"userId": @1,
        @"page": @1,
        @"limit": @10
    };
    
    [IMNetworkUtils GET:@"/posts"
             parameters:params
                success:^(IMNetworkResponse *response) {
                    NSLog(@"✅ 带参数GET请求成功，获取到 %lu 条数据", 
                          [(NSArray *)response.data count]);
                }
                failure:^(IMNetworkResponse *response) {
                    NSLog(@"❌ 带参数GET请求失败: %@", response.error.localizedDescription);
                }];
}

+ (void)demonstratePOSTRequest {
    NSLog(@"\n--- POST请求示例 ---");
    
    // 创建用户
    NSDictionary *userParams = @{
        @"title": @"测试标题",
        @"body": @"这是一个测试内容",
        @"userId": @1
    };
    
    [IMNetworkUtils POST:@"/posts"
              parameters:userParams
                 success:^(IMNetworkResponse *response) {
                     NSLog(@"✅ POST请求成功:");
                     NSLog(@"创建的数据: %@", response.data);
                     NSLog(@"请求ID: %@", response.requestID);
                 }
                 failure:^(IMNetworkResponse *response) {
                     NSLog(@"❌ POST请求失败: %@", response.error.localizedDescription);
                 }];
    
    // 带自定义头的请求
    NSDictionary *headers = @{
        @"Authorization": @"Bearer your-token-here",
        @"X-Custom-Header": @"CustomValue"
    };
    
    [IMNetworkUtils request:IMNetworkMethodPOST
                  URLString:@"/posts"
                 parameters:userParams
                    headers:headers
                    success:^(IMNetworkResponse *response) {
                        NSLog(@"✅ 带自定义头的POST请求成功");
                    }
                    failure:^(IMNetworkResponse *response) {
                        NSLog(@"❌ 带自定义头的POST请求失败");
                    }];
}

+ (void)demonstrateFileOperations {
    NSLog(@"\n--- 文件操作示例 ---");
    
    // 模拟文件上传
    NSString *testString = @"这是一个测试文件内容，用于演示文件上传功能。";
    NSData *fileData = [testString dataUsingEncoding:NSUTF8StringEncoding];
    
    // 注意：这里使用的是演示URL，实际使用时需要替换为真实的上传接口
    /*
    [IMNetworkUtils uploadFile:@"/upload"
                    parameters:@{@"description": @"测试文件"}
                      fileData:fileData
                          name:@"file"
                      fileName:@"test.txt"
                      mimeType:@"text/plain"
                      progress:^(NSProgress *progress) {
                          NSLog(@"📤 上传进度: %.1f%%", progress.fractionCompleted * 100);
                      }
                       success:^(IMNetworkResponse *response) {
                           NSLog(@"✅ 文件上传成功: %@", response.data);
                       }
                       failure:^(IMNetworkResponse *response) {
                           NSLog(@"❌ 文件上传失败: %@", response.error.localizedDescription);
                       }];
    */
    
    // 文件下载示例
    NSString *downloadURL = @"https://jsonplaceholder.typicode.com/posts/1";
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *filePath = [documentsPath stringByAppendingPathComponent:@"downloaded_post.json"];
    
    [IMNetworkUtils downloadFile:downloadURL
                     destination:filePath
                        progress:^(NSProgress *progress) {
                            NSLog(@"📥 下载进度: %.1f%%", progress.fractionCompleted * 100);
                        }
                         success:^(IMNetworkResponse *response) {
                             NSLog(@"✅ 文件下载成功，保存到: %@", response.data[@"filePath"]);
                         }
                         failure:^(IMNetworkResponse *response) {
                             NSLog(@"❌ 文件下载失败: %@", response.error.localizedDescription);
                         }];
}

+ (void)demonstrateNetworkMonitoring {
    NSLog(@"\n--- 网络状态监控示例 ---");
    
    // 检查当前网络状态
    NSLog(@"📶 当前网络状态: %@", [IMNetworkUtils networkStatus]);
    NSLog(@"🌐 网络是否可达: %@", [IMNetworkUtils isNetworkReachable] ? @"是" : @"否");
    NSLog(@"📶 是否WiFi网络: %@", [IMNetworkUtils isWiFiNetwork] ? @"是" : @"否");
    
    // 开始网络状态监控
    [IMNetworkUtils startNetworkMonitoring:^(NSString *status) {
        NSLog(@"📱 网络状态变化: %@", status);
        
        // 根据网络状态调整策略
        if ([status isEqualToString:@"NotReachable"]) {
            NSLog(@"⚠️ 网络不可达，暂停网络请求");
            [IMNetworkUtils cancelAllRequests];
        } else if ([status isEqualToString:@"ReachableViaWWAN"]) {
            NSLog(@"📱 切换到移动网络，调整请求策略");
            // 可以在这里调整超时时间、重试次数等
        } else if ([status isEqualToString:@"ReachableViaWiFi"]) {
            NSLog(@"📶 切换到WiFi网络，恢复正常请求策略");
        }
    }];
}

+ (void)demonstrateRequestManagement {
    NSLog(@"\n--- 请求管理示例 ---");
    
    // 创建多个并发请求
    NSMutableArray<IMNetworkTask *> *tasks = [NSMutableArray array];
    
    for (int i = 1; i <= 5; i++) {
        NSString *url = [NSString stringWithFormat:@"/posts/%d", i];
        IMNetworkTask *task = [IMNetworkUtils GET:url
                                       parameters:nil
                                          success:^(IMNetworkResponse *response) {
                                              NSLog(@"✅ 并发请求 %@ 完成", url);
                                          }
                                          failure:^(IMNetworkResponse *response) {
                                              NSLog(@"❌ 并发请求 %@ 失败", url);
                                          }];
        [tasks addObject:task];
    }
    
    NSLog(@"🚀 已发起 %lu 个并发请求", (unsigned long)tasks.count);
    NSLog(@"📊 当前活跃请求数: %ld", (long)[IMNetworkUtils activeRequestCount]);
    
    // 演示取消请求
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 取消第一个任务
        [tasks.firstObject cancel];
        NSLog(@"❌ 已取消第一个请求");
        
        // 取消包含特定URL的请求
        [IMNetworkUtils cancelRequestsWithURL:@"/posts/3"];
        NSLog(@"❌ 已取消包含 '/posts/3' 的请求");
        
        NSLog(@"📊 取消后活跃请求数: %ld", (long)[IMNetworkUtils activeRequestCount]);
    });
}

#pragma mark - 高级示例

+ (void)advancedNetworkExample {
    NSLog(@"========== 网络工具高级示例 ==========");
    
    [self demonstrateSSLConfiguration];
    [self demonstrateCacheManagement];
    [self demonstrateNetworkStatistics];
    [self demonstrateErrorHandling];
}

+ (void)demonstrateSSLConfiguration {
    NSLog(@"\n--- SSL配置示例 ---");
    
    // 配置SSL验证（开发环境可能需要）
    [IMNetworkUtils setSSLValidation:YES validatesDomainName:YES];
    NSLog(@"🔒 SSL验证已启用");
    
    // 在生产环境中，可以添加证书锁定
    /*
    NSString *certPath = [[NSBundle mainBundle] pathForResource:@"certificate" ofType:@"cer"];
    NSData *certData = [NSData dataWithContentsOfFile:certPath];
    if (certData) {
        [IMNetworkUtils addSSLCertificate:certData];
        NSLog(@"🔐 SSL证书已添加");
    }
    */
}

+ (void)demonstrateCacheManagement {
    NSLog(@"\n--- 缓存管理示例 ---");
    
    // 设置缓存策略
    [IMNetworkUtils setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
    NSLog(@"💾 缓存策略已设置");
    
    // 获取缓存大小
    NSString *cacheSize = [IMNetworkUtils cacheSize];
    NSLog(@"📊 当前缓存大小: %@", cacheSize);
    
    // 清除缓存
    [IMNetworkUtils clearCache];
    NSLog(@"🗑 缓存已清除");
}

+ (void)demonstrateNetworkStatistics {
    NSLog(@"\n--- 网络统计示例 ---");
    
    // 获取网络统计信息
    NSDictionary *stats = [IMNetworkUtils networkStatistics];
    NSLog(@"📈 网络统计信息:");
    NSLog(@"  总请求数: %@", stats[@"totalRequests"]);
    NSLog(@"  成功请求数: %@", stats[@"successfulRequests"]);
    NSLog(@"  失败请求数: %@", stats[@"failedRequests"]);
    NSLog(@"  总传输字节: %@", stats[@"totalBytes"]);
    NSLog(@"  平均响应时间: %.3fs", [stats[@"averageResponseTime"] doubleValue]);
    
    // 导出网络日志
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *logPath = [documentsPath stringByAppendingPathComponent:@"network_logs.txt"];
    
    BOOL success = [IMNetworkUtils exportNetworkLogs:logPath];
    if (success) {
        NSLog(@"📄 网络日志已导出到: %@", logPath);
    }
}

+ (void)demonstrateErrorHandling {
    NSLog(@"\n--- 错误处理示例 ---");
    
    // 测试超时错误
    IMNetworkConfig *config = [IMNetworkUtils currentConfig];
    config.timeoutInterval = 1.0; // 设置很短的超时时间
    [IMNetworkUtils updateConfig:config];
    
    [IMNetworkUtils GET:@"/posts/1"
             parameters:nil
                success:^(IMNetworkResponse *response) {
                    NSLog(@"✅ 请求成功（不应该发生）");
                }
                failure:^(IMNetworkResponse *response) {
                    NSLog(@"❌ 预期的超时错误:");
                    NSLog(@"  错误码: %ld", (long)response.error.code);
                    NSLog(@"  错误描述: %@", response.error.localizedDescription);
                    NSLog(@"  请求ID: %@", response.requestID);
                    NSLog(@"  耗时: %.3fs", response.duration);
                }];
    
    // 恢复正常超时时间
    config.timeoutInterval = 30.0;
    [IMNetworkUtils updateConfig:config];
    
    // 测试404错误
    [IMNetworkUtils GET:@"/nonexistent-endpoint"
             parameters:nil
                success:^(IMNetworkResponse *response) {
                    NSLog(@"✅ 请求成功（不应该发生）");
                }
                failure:^(IMNetworkResponse *response) {
                    NSLog(@"❌ 404错误处理:");
                    NSLog(@"  状态码: %ld", (long)response.statusCode);
                    NSLog(@"  错误: %@", response.error.localizedDescription);
                }];
}

#pragma mark - 实际应用示例

+ (void)realWorldExample {
    NSLog(@"========== 实际应用示例 ==========");
    
    // 模拟广告SDK的网络请求场景
    [self simulateAdSDKNetworkRequests];
}

+ (void)simulateAdSDKNetworkRequests {
    NSLog(@"\n--- 广告SDK网络请求模拟 ---");
    
    // 1. 初始化配置
    [self initializeAdSDKNetwork];
    
    // 2. 获取广告配置
    [self fetchAdConfiguration];
    
    // 3. 请求广告
    [self requestAds];
    
    // 4. 上报广告事件
    [self reportAdEvents];
}

+ (void)initializeAdSDKNetwork {
    IMNetworkConfig *adConfig = [IMNetworkConfig defaultConfig];
    adConfig.baseURL = @"https://api.adsdk.example.com";
    adConfig.defaultHeaders = @{
        @"Authorization": @"Bearer your-api-key",
        @"X-SDK-Version": @"1.0.0",
        @"X-Platform": @"iOS",
        @"Content-Type": @"application/json"
    };
    adConfig.timeoutInterval = 15.0;
    adConfig.enableRetry = YES;
    adConfig.maxRetryCount = 3;
    
    [IMNetworkUtils initWithConfig:adConfig];
    NSLog(@"🎯 广告SDK网络配置已初始化");
}

+ (void)fetchAdConfiguration {
    NSDictionary *params = @{
        @"app_id": @"your-app-id",
        @"device_id": [IMDeviceUtils deviceIdentifier],
        @"os_version": [IMDeviceUtils systemVersion],
        @"sdk_version": @"1.0.0"
    };
    
    [IMNetworkUtils GET:@"/v1/config"
             parameters:params
                success:^(IMNetworkResponse *response) {
                    NSLog(@"✅ 广告配置获取成功");
                    // 处理配置数据
                    [self processAdConfiguration:response.data];
                }
                failure:^(IMNetworkResponse *response) {
                    NSLog(@"❌ 广告配置获取失败: %@", response.error.localizedDescription);
                    // 使用本地缓存配置
                    [self useLocalAdConfiguration];
                }];
}

+ (void)requestAds {
    NSDictionary *adRequest = @{
        @"placement_id": @"banner_main",
        @"ad_format": @"banner",
        @"size": @"320x50",
        @"user_consent": @YES,
        @"location": @{
            @"country": @"CN",
            @"city": @"Beijing"
        }
    };
    
    [IMNetworkUtils POST:@"/v1/ads/request"
              parameters:adRequest
                 success:^(IMNetworkResponse *response) {
                     NSLog(@"✅ 广告请求成功");
                     [self processAdResponse:response.data];
                 }
                 failure:^(IMNetworkResponse *response) {
                     NSLog(@"❌ 广告请求失败: %@", response.error.localizedDescription);
                     [self handleAdRequestFailure:response.error];
                 }];
}

+ (void)reportAdEvents {
    // 广告展示事件
    NSDictionary *showEvent = @{
        @"event_type": @"impression",
        @"ad_id": @"ad_12345",
        @"placement_id": @"banner_main",
        @"timestamp": @([[NSDate date] timeIntervalSince1970] * 1000),
        @"session_id": [[NSUUID UUID] UUIDString]
    };
    
    [IMNetworkUtils POST:@"/v1/events"
              parameters:showEvent
                 success:^(IMNetworkResponse *response) {
                     NSLog(@"✅ 广告展示事件上报成功");
                 }
                 failure:^(IMNetworkResponse *response) {
                     NSLog(@"❌ 广告展示事件上报失败，将缓存本地");
                     [self cacheEventForLaterRetry:showEvent];
                 }];
    
    // 广告点击事件
    NSDictionary *clickEvent = @{
        @"event_type": @"click",
        @"ad_id": @"ad_12345",
        @"placement_id": @"banner_main",
        @"click_position": @{@"x": @150, @"y": @25},
        @"timestamp": @([[NSDate date] timeIntervalSince1970] * 1000)
    };
    
    [IMNetworkUtils POST:@"/v1/events"
              parameters:clickEvent
                 success:^(IMNetworkResponse *response) {
                     NSLog(@"✅ 广告点击事件上报成功");
                 }
                 failure:^(IMNetworkResponse *response) {
                     NSLog(@"❌ 广告点击事件上报失败");
                 }];
}

+ (void)processAdConfiguration:(NSDictionary *)config {
    NSLog(@"📝 处理广告配置: %@", config);
    // 实际处理逻辑...
}

+ (void)useLocalAdConfiguration {
    NSLog(@"💾 使用本地缓存的广告配置");
    // 加载本地配置逻辑...
}

+ (void)processAdResponse:(NSDictionary *)adData {
    NSLog(@"🎯 处理广告响应: %@", adData);
    // 实际广告处理逻辑...
}

+ (void)handleAdRequestFailure:(NSError *)error {
    NSLog(@"⚠️ 处理广告请求失败: %@", error.localizedDescription);
    // 错误处理逻辑，比如降级策略...
}

+ (void)cacheEventForLaterRetry:(NSDictionary *)event {
    NSLog(@"💾 缓存事件以便稍后重试: %@", event[@"event_type"]);
    // 本地缓存逻辑...
}

@end

#pragma mark - 使用入口

// 在需要的地方调用这些示例方法
void RunNetworkExamples() {
    NSLog(@"🚀 开始运行网络工具示例...\n");
    
    // 运行基础示例
    [NSObject basicNetworkExample];
    
    // 等待一段时间后运行高级示例
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [NSObject advancedNetworkExample];
    });
    
    // 再等待一段时间后运行实际应用示例
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [NSObject realWorldExample];
    });
} 